package com.kevin.action.back;

import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.QueryResult;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.View;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.By;
import org.nutz.mvc.annotation.Fail;
import org.nutz.mvc.annotation.Filters;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import org.nutz.mvc.filter.CheckSession;
import org.nutz.mvc.view.JspView;

import com.kevin.action.BaseAction;
import com.kevin.common.DwzoutMapUtil;
import com.kevin.common.PassUtil;
import com.kevin.common.RequestParamUtil;
import com.kevin.dao.ManagerDao;
import com.kevin.model.Manager;
import com.kevin.model.Role;
import com.kevin.util.SystemContext;

/**
 * 
  * @ClassName: IndexAction 
  * @Description: 首页模块
  * @author 吕凯
  * @date 2012-10-29 上午10:25:02 
  *
 */
@IocBean
@At("/admin/system")
@Filters( { @By(type = CheckSession.class, args = { "admin", "/admin/loginp.shtml" }) })
public class SystemAction  extends BaseAction{
	@Inject
	private ManagerDao managerDao;
	
	/**
	 * 
	  * @方法名  cache 
	  * @功能描述  垃圾收集
	  * @author   吕凯  
	  * @return 
	  * @return  Map<String,Object> 
	  * @编码时间 2012-11-2 下午04:26:45
	 */
	@At
	@Ok("json")
	@Fail("json")
	public Map<String, Object> cache() {
		Runtime runtime = Runtime.getRuntime();
		runtime.gc();
		Map<String, Object> map = DwzoutMapUtil.getSuccDwzoutMap("垃圾收集成功！", "cache", "", "", "", "");
		return map;
	}
	@At
	@Ok("jsp:/jsp/back/system/cache.jsp")
	@Fail("jsp:error.404")
	public void showcache(HttpServletRequest req) {
		Runtime runtime = Runtime.getRuntime();
		DecimalFormat mbFormat = new DecimalFormat("#0.00");
		DecimalFormat percentFormat = new DecimalFormat("#0.0");
		int NUM_BLOCKS = 50;
		double freeMemory = (double)runtime.freeMemory()/(1024*1024);
		double totalMemory = (double)runtime.totalMemory()/(1024*1024);
		double maxMemory = Runtime.getRuntime().maxMemory()/(1024*1024);
		double usedMemory = totalMemory - freeMemory;
		double percentFree = ((double)freeMemory/(double)totalMemory)*100.0;
		int free = 100-(int)Math.round(percentFree);
		req.setAttribute("usedMemory", mbFormat.format(usedMemory));//已用内存
		req.setAttribute("totalMemory", mbFormat.format(totalMemory));//内存总量
		req.setAttribute("maxMemory", mbFormat.format(maxMemory));//最大内存
		req.setAttribute("availableProcessors", runtime.availableProcessors());//处理器数
		req.setAttribute("num_blocks", NUM_BLOCKS);//分的块数
		req.setAttribute("percentFree", percentFormat.format(percentFree));//空闲率
		req.setAttribute("free", free);//使用的百分值
	}
	
	/**
	 * 分页查询出用户信息
	 * 
	 * @param currentPage
	 * @param pageSize
	 * @param ioc
	 * @return
	 */
	@At()
	public View showuserslist(@Param("pageNum") int currentPage, HttpServletRequest req) {

		if(currentPage == 0)
			currentPage = 1;
		Integer pageSize = 10;
		try {
			pageSize = Integer.parseInt(req.getParameter("numPerPage"));
		} catch (NumberFormatException e) {}
		SqlExpressionGroup group = RequestParamUtil.dealRequest(req);
		QueryResult qr = basicDao.searchByPageData(Manager.class, currentPage,
				pageSize, Cnd.where(group).desc("id"));	

		req.setAttribute("qr", qr);

		return new JspView("/jsp/back/system/showuserslist");
	}
	/**
	 * 根据id查找数据
	 * 
	 * @param id
	 * @param ioc
	 * @return
	 */
	@At()
	public View editUserInfo(@Param("id") int id, HttpServletRequest req) {
		if(id != 0){
			Manager user = managerDao.find(id, Manager.class);
			if(user != null){
				user.setPassword(PassUtil.decryptPass(user.getPassword()));
				req.setAttribute("obj", user);				
			}
		}
		return new JspView("/jsp/back/system/editUserInfo");
	}
	/**
	 * 根据id修改密码
	 * 
	 * @param id
	 * @param ioc
	 * @return
	 */
	@At()
	@Ok("json")
	@Fail("json")
	public Map<String, Object> updateuserinfo(@Param("..") Manager user,
							@Param("oldpwd") String oldpwd,
							HttpServletRequest req) {
		String msg = "用户信息修改失败！";
		int id = user.getId();
		Map<String, Object> returnMap = DwzoutMapUtil.getErrDwzoutMap(msg);
		boolean flag =  false;
		if(id == 0){//增加
			msg = "新增用户失败！";
			user.setPassword(PassUtil.encryptPass(user.getPassword()));
			user.setLastLoginIp(req.getRemoteAddr());
			managerDao.save(user);
			flag = true;
			msg = "新增用户成功！";
		}else{//修改
			Manager man = managerDao.find(user.getId(), Manager.class);	
			man.setUsername(user.getUsername());
			man.setState(user.isState());
			man.setPassword(PassUtil.encryptPass(user.getPassword()));
			flag = managerDao.update(man);
			msg = "用户信息修改成功！";
		}
		if(flag)
			returnMap = DwzoutMapUtil.getSuccDwzoutMap(msg,req.getParameter("navTabId"),"","closeCurrent","","");
		return returnMap;
	}
	/**
	 * 分配角色
	 * 
	 * @param id
	 * @param role
	 * @param action
	 * @param ioc
	 * @return
	 */
	@At("role")
	@Ok("Json")
	public String setRole(	@Param("id") int id,
							@Param("role") int role,
							@Param("action") boolean action) {

		if (action) {
			managerDao.save("t_manager_role", Chain.make("manager_id", id).add("role_id", role));
		} else {
			managerDao.delete(	"t_manager_role",
								Cnd.where("manager_id", "=", id).and("role_id", "=", role));
		}

		return "{success:true}";

	}
	//=============================================角色设置开始=========================================
	/**
	 * 分页查询出角色信息
	 * 
	 * @param currentPage
	 * @param pageSize
	 * @param ioc
	 * @return
	 */
	@At("/showroleslist")
	public View list(@Param("pageNum") int currentPage,
			HttpServletRequest req) {

		if(currentPage == 0)
			currentPage = 1;
		Integer pageSize = 10;
		try {
			pageSize = Integer.parseInt(req.getParameter("numPerPage"));
		} catch (NumberFormatException e) {}

//		RoleDaobasicDao = new RoleDao(ioc);

		QueryResult qr = basicDao.searchByPageData(Role.class, currentPage,
				pageSize, Cnd.orderBy().desc("id"));	

		req.setAttribute("qr", qr);
		return new JspView("/jsp/back/system/showroleslist");
	}
	/**
	 * 根据用户id查询用户角色
	 * 
	 * @param currentPage
	 * @param pageSize
	 * @param ioc
	 * @return
	 */
	@At("/roleset")
	public View setRole(@Param("uid") int uid,HttpServletRequest req){
		Manager m = managerDao.find(uid, Manager.class);
		
		m = managerDao.findLink(m, "roles");
		
		req.setAttribute("data", m);
		
//		RoleDao rdao = new RoleDao(ioc);
		
		List<Role> roles = basicDao.search(Role.class, "rule");
		req.setAttribute("roles", roles);
		req.setAttribute("a", roles);
		
		return new JspView("/jsp/back/system/assignRoles");
	}
	/**
	 * 编辑用户角色
	 * 
	 * @param currentPage
	 * @param pageSize
	 * @param ioc
	 * @return
	 */
	@At("/edituserroles")
	@Ok("json")
	@Fail("json")
	public Map<String, Object> editUserRoles(@Param("uid") int uid,@Param("roles") int[] ids,HttpServletRequest req){
		Manager m = managerDao.find(uid, Manager.class);
		if(m == null)
			return DwzoutMapUtil.getErrDwzoutMap("没有该用户！");
		Map<String, Object> returnMap = DwzoutMapUtil.getSuccCloseDwzoutMap("修改角色成功");		
		m = managerDao.findLink(m, "roles");		
		req.setAttribute("m", m);
		List<Role> list = basicDao.searchByIds(Role.class, ids, "id");
		m.setRoles(list);
		basicDao.clearRelation(m, "roles");
		basicDao.saveRelation(m, "roles");	
		
		return returnMap;
	}
	/**
	 * 删除用户
	 * 
	 * @param currentPage
	 * @param pageSize
	 * @param ioc
	 * @return
	 */
	@At("/deluser")
	@Ok("json")
	@Fail("json")
	public Map<String, Object> delUser(@Param("uid") int uid,HttpServletRequest req){
		Manager m = managerDao.find(uid, Manager.class);
		if(m == null)
			return DwzoutMapUtil.getErrDwzoutMap("没有该用户！");
		m = managerDao.findLink(m, "roles");
		Map<String, Object> returnMap = DwzoutMapUtil.getSuccDwzoutMap("删除用户成功");		
		basicDao.clearRelation(m, "roles");
		basicDao.delObj(m);

		return returnMap;
	}
	/**
	 * 添加一条数据信息
	 * 
	 * @param role
	 * @param ioc
	 * @return
	 */
	@At("/admin/role/add")
	@Ok("json")
	public String add(@Param("::role.") Role role) {

//		RoleDaobasicDao = new RoleDao(ioc);

		boolean flag = false;

		if (role.getId() == 0) {
			role =basicDao.save(role);
			flag = !flag;
		} else {
			if (basicDao.update(role)) {
				flag = !flag;
			}
		}

		StringBuffer sb = new StringBuffer("{");
		if (role != null) {
			sb.append("id:").append(role.getId()).append(",");
			sb.append("name:'").append(role.getName()).append("',");
			sb.append("rule:").append(role.getRule());
		} else {
			sb.append("id:").append(0);
		}
		sb.append("}");

		if (flag) {
			return "[{success:true}," + sb.toString() + "]";
		}

		return "[{success:false}]";
	}

	/**
	 * 根据id删除数据信息
	 * 
	 * @param id
	 * @param ioc
	 * @return
	 */
	@At("/admin/role/del")
	@Ok("json")
	public String del(@Param("id") int id,@Param("currentPage") int currentPage) {
		
//		RoleDaobasicDao = new RoleDao(ioc);
		
		int count =basicDao.searchCount(Role.class);
		int maxPage =basicDao.maxPageSize(count, SystemContext.PAGE_SIZE);
		
		StringBuffer sb = new StringBuffer("[");
		if (maxPage > 1) {
			List<Role> roles =basicDao.searchByPage(Role.class, (currentPage + 1),SystemContext.PAGE_SIZE, "id");
			for (Role role : roles) {
				sb.append("{");
				sb.append("id:").append(role.getId()).append(",");
				sb.append("name:'").append(role.getName()).append("',");
				sb.append("rule:").append(role.getRule());
				sb.append("}");
				//第一次执行完就停止执行
				break;
			}
		}
		sb.append("]");
		
		if (basicDao.delById(id, Role.class)) {	
			return sb.toString();
		}else{
			return "[]";
		}
	}

	/**
	 * 根据ids删除数据信息
	 * 
	 * @param ids
	 * @param ioc
	 * @return
	 */
	@At("/admin/role/delByIds")
	@Ok("json")
	public String delByIds(@Param("ids") String ids,
			@Param("currentPage") int currentPage, @Param("size") int size) {

//		RoleDaobasicDao = new RoleDao(ioc);

		int count =basicDao.searchCount(Role.class);
		int maxPage =basicDao.maxPageSize(count, SystemContext.PAGE_SIZE);
		String str ="";
		StringBuffer sb = new StringBuffer("[");
		if (maxPage > 1) {
			List<Role> roles =basicDao.searchByPage(Role.class, (currentPage + 1),SystemContext.PAGE_SIZE, "id");
			int i=0;
			for (Role role : roles) {
				if(i==size){
					break;
				}else{
					sb.append("{");
					sb.append("id:").append(role.getId()).append(",");
					sb.append("name:'").append(role.getName()).append("',");
					sb.append("rule:").append(role.getRule());
					sb.append("},");
					i++;
				}
			}
		}
		str = sb.toString();
		int dot = str.lastIndexOf(",");
		if (dot != -1) {
			str = str.substring(0, dot);
		}
		basicDao.deleteByIds(Role.class, ids);
		
		return str+"]";
	}

	/**
	 * 根据id查找数据
	 * 
	 * @param id
	 * @param ioc
	 * @return
	 */
	@At("/admin/role/find")
	@Ok("json")
	public String find(@Param("id") int id) {

//		RoleDaobasicDao = new RoleDao(ioc);

		Role role =basicDao.find(id, Role.class);

		StringBuffer sb = new StringBuffer("{");
		if (role != null) {
			sb.append("id:").append(role.getId()).append(",");
			sb.append("name:'").append(role.getName()).append("',");
			sb.append("rule:").append(role.getRule());
		} else {
			sb.append("id:").append(0);
		}
		sb.append("}");

		return sb.toString();
	}
	/**
	 * 分配权限
	 * @param ioc
	 * @param id
	 * @param req
	 * @return
	 */
	@At("/admin/role/permission")
	public View setPermission(@Param("id") int id,HttpServletRequest req){
		
//		RoleDaobasicDao = new RoleDao(ioc);
		
		Role role =basicDao.find(id, Role.class);
		
		role =basicDao.findLink(role, "permission");
		
		req.setAttribute("role", role);
		
		return new JspView("admin.permission");
	}
	
	
	//=============================================角色设置结束==========================================
}
